package com.rizzo.shell.intern;

import com.google.common.base.Strings;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import java.util.HashMap;
import java.util.Map;

public abstract class RizzoCommands {

    public static final int WIDE_TAB_PADDING = 50;
    public static final int MEDIUM_TAB_PADDING = 25;
    public static final int SHORT_TAB_PADDING = 15;

    protected static final String DUMMY_SPACE = " ";
    protected static final char PADDING_CHAR = ' ';

    protected static int safeLongToInt(long l) {
        if (l < Integer.MIN_VALUE || l > Integer.MAX_VALUE) {
            throw new IllegalArgumentException
                    (l + " cannot be cast to int without changing its value.");
        }
        return (int) l;
    }

    protected static String tabValues(int tabPadding, String... values) {
        StringBuilder tabbedString = new StringBuilder();
        for (String value : values) {
            if (value != null) {
                tabbedString.append(Strings.padEnd(value, tabPadding, PADDING_CHAR));
            } else {
                tabbedString.append(Strings.padEnd(DUMMY_SPACE, tabPadding, PADDING_CHAR));
            }
        }
        return tabbedString.toString();
    }

    protected AnnotationConfigApplicationContext getApplicationContext(String argsBeanName, Map args, Class... clazz) {
        BeanDefinition beanDefinition = BeanDefinitionBuilder.rootBeanDefinition(HashMap.class).addConstructorArgValue(args).getBeanDefinition();
        AnnotationConfigApplicationContext componentContext = new AnnotationConfigApplicationContext();
        componentContext.registerBeanDefinition(argsBeanName, beanDefinition);
        componentContext.register(clazz);
        componentContext.refresh();
        return componentContext;
    }

}
